import React from 'react';
import MainUI from '../../components/layout/MainUI';
import RichTextEditor from '../../components/common/RichTextEditor';
import {connect} from 'dva';
import { Map,Marker } from 'react-amap';

import moment from 'moment';
import {
  Breadcrumb,
  Button,
  Col,
  Form,
  Row,
  Icon,
  Input,
  Modal,
  Upload,
  message,
} from 'antd';

const FormItem = Form.Item;
const params = {};
const formItemLayout = {
  labelCol: {span: 5},
  wrapperCol: {span: 19},
};

class MyMerchant extends React.Component {

  state = {
    editable: false,
    previewVisible: false,
    previewImage: '',
    position:undefined,
    context:'',
  };


  uploadCancel = () => this.setState({previewVisible: false});
  handlePreview = (file) => {
    this.setState({
      previewImage: file.url,
      previewVisible: true,
    });
  };
  logoHandleChange = (info) => {
    let logoFileList = info.fileList;
    logoFileList = logoFileList.map((file) => {
      if (file.response) {
        if (file.response.status === 200) {
          file.url = file.response.data;
          file.thumbUrl = file.response.data;
          file.status = 'done';
        } else {
          file.status = 'error';
          message.error("文件上传失败");
          return null;
        }
      }
      return file;
    });
    const newfilelist = [];
    for (const f of logoFileList) {
      if (f != null) {
        newfilelist.push(f);
      }
    }
    this.props.dispatch({
      type: 'merchant/e_updateLogoFileList',
      payload:newfilelist,
    });
  };
  scrollLogosHandleChange = (info) => {
    let scrollLogos = info.fileList;
    scrollLogos = scrollLogos.map((file) => {
      if (file.response) {
        if (file.response.status === 200) {
          file.url = file.response.data;
          file.thumbUrl = file.response.data;
          file.status = 'done';
        } else {
          file.status = 'error';
          message.error("文件上传失败",2);
          return null;
        }
      }
      return file;
    });
    const newfilelist = [];
    for (const f of scrollLogos) {
      if (f != null) {
        newfilelist.push(f);
      }
    }
    this.props.dispatch({
      type: 'merchant/e_updateScrollLogosFileList',
      payload:newfilelist,
    });
  };

  search = () => {
    this.props.dispatch({
      type: 'merchant/e_updateContext',
      payload:{context:this.state.context},
    });
    this.props.dispatch({
      type: 'merchant/getMyMerchant',
    });
  };
  toEdit = () => {
    const state = this.state;
    state.editable = true;
    this.setState(state);
  };
  edit = () => {
    this.props.form.validateFieldsAndScroll((errors, values) => {
      if (errors) {

      } else {
        if (this.props.logoFileList.length != 0) {
          values.log = this.props.logoFileList[0].url;
        }
        values.scrollLogos = this.props.scrollLogosFileList.map((ob) => {
          return ob.url;
        });
        values.context = this.state.context;
        this.props.dispatch({
          type: 'merchant/e_update',
          payload: values
        });
        const state = this.state;
        state.editable = false;
        this.setState(state);
      }
    });
  };

  amapEvents=()=>{
    return {
      dblclick: (params) => {
        this.props.dispatch({
          type: 'merchant/e_updateLotLat',
          payload:{longitude: params.lnglat.lng, latitude: params.lnglat.lat}
        });
      }
    }
  };

  updateContent=(context)=>{
    const state=this.state;
    state.context=context;
    this.setState(state);
  };

  render() {
    return (
      <MainUI>
        <Breadcrumb style={{margin: '12px 0'}}>
          <Breadcrumb.Item>系统管理</Breadcrumb.Item>
          <Breadcrumb.Item> 店铺信息</Breadcrumb.Item>
        </Breadcrumb>
        <div style={{padding: 24, background: '#fff', minHeight: 360,}}>
          <Row>
            <Col span={24} style={{textAlign: 'right'}}>
              <Button type="primary" icon="retweet" onClick={() => {
                this.search();
              }}>刷新</Button>
              <span className="ant-divider"/>
              {
                this.state.editable === false ? <Button onClick={() => {
                  this.toEdit()
                }}> 编辑</Button> : <Button onClick={() => {
                  this.edit()
                }}> 保存</Button>
              }
            </Col>
          </Row>
          <Row>
            <Col offset={1} span={20}>
              {
                this.props.myMerchant != undefined ? <Form>
                  <Row>
                    {
                      this.props.form.getFieldDecorator('id', {
                          initialValue: this.props.myMerchant.id,
                          rules: [
                            {required: true,},
                          ],
                        }
                      )(
                        <Input type='hidden' disabled={!this.state.editable}/>
                      )
                    }
                    <FormItem {...formItemLayout} label='店铺名称' labelCol={{span: 4}} wrapperCol={{span: 10}}>
                      {
                        this.props.form.getFieldDecorator('name', {
                          initialValue: this.props.myMerchant.name,
                        })(
                          <Input placeholder="店铺名称" size='large' disabled={!this.state.editable}/>
                        )
                      }
                    </FormItem>
                  </Row>
                  <Row>
                    <FormItem {...formItemLayout} label='地址' labelCol={{span: 4}} wrapperCol={{span: 10}}>
                      {
                        this.props.form.getFieldDecorator('address', {
                          initialValue: this.props.myMerchant.address,
                        })(
                          <Input placeholder="地址" size='large' disabled={!this.state.editable}/>
                        )
                      }
                    </FormItem>
                  </Row>
                  <Row>
                    <FormItem {...formItemLayout} label='到期期时间' labelCol={{span: 4}} wrapperCol={{span: 10}}>
                        <font color='red' size={5}>{ moment(this.props.myMerchant.expireDate).format("YYYY-MM-DD HH:mm:ss") }</font>
                    </FormItem>
                  </Row>
                  <Row>
                    <FormItem {...formItemLayout} label='电话(登录使用)' labelCol={{span: 4}} wrapperCol={{span: 10}}>
                      {
                        this.props.form.getFieldDecorator('cellphone', {
                          initialValue: this.props.myMerchant.cellphone,
                        })(
                          <Input size='large' disabled={true}/>
                        )
                      }
                    </FormItem>
                  </Row>
                  <Row>
                    <FormItem {...formItemLayout} label='联系方式' labelCol={{span: 4}} wrapperCol={{span: 10}}>
                      {
                        this.props.form.getFieldDecorator('linkMe', {
                          initialValue: this.props.myMerchant.linkMe,
                        })(
                          <Input size='large' disabled={!this.state.editable}/>
                        )
                      }
                    </FormItem>
                  </Row>
                  <Row>
                    <FormItem {...formItemLayout} label='营业时间' labelCol={{span: 4}} wrapperCol={{span: 10}}>
                      {
                        this.props.form.getFieldDecorator('work', {
                          initialValue: this.props.myMerchant.work,
                        })(
                          <Input size='large' disabled={!this.state.editable}/>
                        )
                      }
                    </FormItem>
                  </Row>
                  <Row>
                    <FormItem {...formItemLayout} label='logo' labelCol={{span: 4}} wrapperCol={{span: 10}}>
                      <Upload
                        action={"/api/system/file/upload?accessToken=" + JSON.parse(window.sessionStorage.getItem("accessToken"))}
                        listType="picture-card"
                        fileList={this.props.logoFileList}
                        onPreview={this.handlePreview}
                        onChange={this.logoHandleChange}
                      >
                        {
                          this.props.logoFileList.length >= 1 ? null : <div>
                            <Icon type="plus"/>
                            <div className="ant-upload-text">上传</div>
                          </div>
                        }
                      </Upload>
                      <Modal visible={this.state.previewVisible} footer={null} onCancel={this.uploadCancel}>
                        <img alt="example" style={{width: '100%'}} src={this.state.previewImage}/>
                      </Modal>
                    </FormItem>
                  </Row>
                  <Row>
                    <FormItem {...formItemLayout} label='店铺滚动图' labelCol={{span: 4}} wrapperCol={{span: 10}}>
                      <Upload
                        action={"/api/system/file/upload?accessToken=" + JSON.parse(window.sessionStorage.getItem("accessToken"))}
                        listType="picture-card"
                        fileList={this.props.scrollLogosFileList}
                        onPreview={this.handlePreview}
                        onChange={this.scrollLogosHandleChange}
                      >
                        {
                          this.props.scrollLogosFileList.length >= 6 ? null : <div>
                            <Icon type="plus"/>
                            <div className="ant-upload-text">上传</div>
                          </div>
                        }
                      </Upload>
                      <Modal visible={this.state.previewVisible} footer={null} onCancel={this.uploadCancel}>
                        <img alt="example" style={{width: '100%'}} src={this.state.previewImage}/>
                      </Modal>
                    </FormItem>
                  </Row>
                  <Row>
                    <FormItem {...formItemLayout} label='店铺介绍' labelCol={{span: 4}} wrapperCol={{span: 10}}>
                      {
                        this.props.form.getFieldDecorator('desc', {
                          initialValue: this.props.myMerchant.desc,
                        })(
                          <Input.TextArea size="large" rows={5} disabled={!this.state.editable}/>
                        )
                      }
                    </FormItem>
                  </Row>
                  <Row>
                    <Col span={8}>
                      <FormItem {...formItemLayout} label='经度' labelCol={{span: 12}} wrapperCol={{span: 12}}>
                        {
                          this.props.form.getFieldDecorator('longitude', {
                            initialValue: this.props.myMerchant.longitude,
                          })(
                            <Input size='large' disabled={true}/>
                          )
                        }
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem {...formItemLayout} label='纬度' labelCol={{span: 4}} wrapperCol={{span: 14}}>
                        {
                          this.props.form.getFieldDecorator('latitude', {
                            initialValue: this.props.myMerchant.latitude,
                          })(
                            <Input size='large' disabled={true}/>
                          )
                        }
                      </FormItem>
                    </Col>
                  </Row>
                  <Row>
                    <FormItem {...formItemLayout} label={<font color="red">双击改变经纬度</font>} labelCol={{span: 4}} wrapperCol={{span: 20}}>
                    <div  style={{maxWidth:'830px',height: '500px',paddingBottom:'20px'}}>
                      <Map amapkey='8f73e7c68958bdf9cf9cf852fb230636' plugins={[
                        'OverView',
                        'ToolBar',
                      ]}
                           center={ this.props.myMerchant.longitude!=null &&this.props.myMerchant.latitude!=null ?{longitude: this.props.myMerchant.longitude, latitude: this.props.myMerchant.latitude}:''}
                           events={this.amapEvents()}
                      >
                        {
                          this.props.myMerchant.longitude!=null &&this.props.myMerchant.latitude!=null ?<Marker position={{longitude: this.props.myMerchant.longitude, latitude: this.props.myMerchant.latitude }} />:<Marker/>
                        }

                      </Map>
                    </div>
                    </FormItem>
                  </Row>
                  <Row>
                    <FormItem {...formItemLayout} label='图文介绍' labelCol={{span: 4}} wrapperCol={{span:20}}>
                        <RichTextEditor htmlContent={this.props.myMerchant.context} updateContent={this.updateContent} />
                    </FormItem>
                  </Row>
                </Form> : ''
              }
            </Col>
          </Row>
        </div>
      </MainUI>
    );
  }
}

function mapStateToProps(state) {
  return {
    myMerchant: state.merchant.myMerchant,
    logoFileList: state.merchant.logoFileList,
    scrollLogosFileList: state.merchant.scrollLogosFileList,
  }
}

export default connect(mapStateToProps)(Form.create()(MyMerchant));
